import { useState } from "react";
import { useAtomValue } from "jotai";
import { Form, Input, Modal } from "antd";
import {
  createProgram,
  getProgramInfo,
  updateProgram,
} from "@/lib/api/program";
import useFetch from "@/lib/hooks/useFetch";
import getRequestErrorMessage from "@/lib/utils/getRequestErrorMessage";
import { useMessage } from "@/providers/AntdMessageProvider";
import { tokenAtom } from "@/store/user";
import useOnUpdated from "@/lib/hooks/useOnUpdated";

type EditProgramModalProps = {
  visible: boolean;
  type?: "create" | "edit";
  programId?: number;
  onClose: () => void;
  onSuccess: () => void;
};
export default function EditProgramModal(props: EditProgramModalProps) {
  const { type, visible, programId, onClose, onSuccess } = props;
  const [name, setName] = useState("");
  const token = useAtomValue(tokenAtom);
  const message = useMessage();

  const { isLoading: isCreateProgramLoading, refetch: handleCreateProgram } =
    useFetch({
      fetchFn: (name: string) =>
        createProgram(name, token).then((res) => {
          if (res.code !== 200) {
            throw res;
          }
        }),
      onError(error) {
        message.error(getRequestErrorMessage(error));
      },
      onSuccess() {
        message.success("创建成功");
        onSuccess();
        onClose();
      },
    });

  const { isLoading: isProgramInfoLoading, refetch: loadProgramInfo } =
    useFetch({
      fetchFn: () =>
        getProgramInfo(programId!, token).then((res) => {
          if (res.code !== 200) {
            throw res;
          }
          return res.data;
        }),
      onSuccess(data) {
        setName(data.programName);
      },
    });

  const { isLoading: isUpdateProgramLoading, refetch: handleUpdateProgram } =
    useFetch({
      fetchFn: (programName: string) =>
        updateProgram({ programName, programId: programId! }, token).then(
          (res) => {
            if (res.code !== 200) {
              throw res;
            }
          },
        ),
      onError(error) {
        message.error(getRequestErrorMessage(error));
      },
      onSuccess() {
        message.success("更新成功！");
        onSuccess();
        onClose();
      },
    });

  useOnUpdated(() => {
    if (visible && type === "edit" && programId !== undefined) {
      loadProgramInfo();
    }
  }, [visible, type, programId]);

  function handleSubmit() {
    if (!name) {
      message.error("请输入程序名称");
      return;
    }
    if (type === "create") {
      handleCreateProgram(name);
    } else {
      handleUpdateProgram(name);
    }
  }

  return (
    <Modal
      title={type === "create" ? "添加程序" : "编辑程序"}
      open={visible}
      onClose={onClose}
      onCancel={onClose}
      onOk={handleSubmit}
      loading={isProgramInfoLoading}
      confirmLoading={isCreateProgramLoading || isUpdateProgramLoading}
      afterClose={() => setName("")}
      destroyOnClose
    >
      <Form>
        <Form.Item label="程序名称" required>
          <Input
            value={name}
            onInput={(e) => setName((e.target as HTMLInputElement).value)}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
}
